<?php
namespace app\index\controller;

use app\api\job\PlayerReport;
use think\cache\driver\Redis;
use think\Db;
use app\common\model\Player;
use app\common\controller\IndexBase;
use app\common\model\Gameulog;
use app\common\controller\Sms;
use think\facade\Session;
use think\Queue;
/**
 * 后台首页
 * 游戏、渠道、日期、新增用户、新增角色、活跃人数、付费金额、付费人数、付费次数、ARPU、ARPPU
 * Class Index
 * @package app\admin\controller
 */
class Login extends IndexBase
{
    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 注册
     * @return void
     */
    public function register(){
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Player');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                unset($data['verify']);
                $data['password'] = get_encrypt($data['password']);
                try {
                    Db::startTrans();
                    Player::register($data);
                    Db::commit();
                    $this->success('注册成功');
                }catch (Exception $e) {
                    Db::rollback();
                    $this->error('注册失败');
                }
            }
        }
    }

    /**
     * 登录
     * @return void
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $password = get_encrypt($data['password']);
            $where['account'] = $data['account'];
            $player = Player::getOne($where);
            if(empty($player)){
                $this->error('账号不存在');
            }
            if($player['status'] == 0){
                $this->error('账号已被禁用');
            }
            if($player['password'] != $password){
                $this->error('密码错误');
            }
            //记录登录信息
            $data['uid'] = $player['id'];
            Gameulog::addLog($data);
            $token = get_encrypt($player['id']);
            $this->token = $token;
            $player['token'] = $token;
            $time = time();
            $player['login_time'] = $time;
            $player['update_time'] = $time;
            $is_fcm = $player['is_age'] == 1 ? 1 : 0;
            unset($player['password']);
            //redis 保存用户信息
            $redis = new Redis();
            $redis->set($token, $player);

            $game = $this->game;
            if (strpos($game['api_login_url'], '?') !== false) {
                $game_url = $game['api_login_url']."&token=".$token;
            } else {
                $game_url = $game['api_login_url']."?token=".$token;
            }
            //添加redis队列、通知到游戏
//            Queue::push(PlayerReport::class, ['uid' => $player['id'],'gid'=>$this->gid]);
            $this->success('登录成功','',['game_url'=>$game_url,'token'=>$token,'age_status'=>$player['is_age'],'is_fcm'=>$is_fcm]);
        }
    }

    public function phoneLogin()
    {
        $data = $this->request->request();
        $phone = $data['phone'];
        $code = $data['code'];
        if(!checkSms($phone,$code)){
            $this->error('验证码错误');
        }
        $where['account'] = $phone;
        $player = Player::getOne($where);
        if(empty($player)){
            //注册
            $data['account'] = $phone;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 1;
            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error('登录失败');
            }
        }
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $this->token = $token;
        $player['token'] = $token;
        $time = time();
        $player['login_time'] = $time;
        $player['update_time'] = $time;
        $is_fcm = $player['is_age'] == 1 ? 1 : 0;
        unset($player['password']);
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);

        $game = $this->game;
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }

        //添加redis队列、通知到游戏
//        Queue::push(PlayerReport::class, ['uid' => $player['id'],'gid'=>$this->gid]);
        $this->success('登录成功','',['game_url'=>$game_url,'token'=>$token,'age_status'=>$player['is_age'],'is_fcm'=>$is_fcm]);
    }


    /*public function wxLogin(){
        $data = $this->request->request();
        $code = $data['code'];
        $access_token = $this->get_access_token($code);
        $where['account'] = 'wx_'.$access_token['openid'];
        $player = Player::getOne($where);
        if(empty($player)){
            //注册
            $data['account'] = 'wx_'.$access_token['openid'];
            $data['password'] = get_encrypt('123456');
            $data['type'] = 2;
            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error('登录失败');
            }
        }
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $this->token = $token;
        $player['token'] = $token;
        unset($player['password']);
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);

        $game = $this->game;
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }

        //添加redis队列、通知到游戏
//        Queue::push(PlayerReport::class, ['uid' => $player['id'],'gid'=>$this->gid]);
        $this->success('登录成功','',['game_url'=>$game_url,'token'=>$token]);

    }*/

    public function sendSms(){
        $data = $this->request->request();
        $phone = $data['phone'];
        $validate_result = $this->validate($data, 'sendSms');
        $type = $data['type'] ?? '0';

        if ($validate_result !== true) {
            $this->error($validate_result);
        }
        $rand = rand(100000, 999999); // 验证码
        try {
            $sms = new Sms();
            $templateParams = [
                (string) $rand,'5'
            ];
//            Queue::push(GaodeReport::class, ['phone' => $phone, 'data' => $templateParams]);
            // 单发短信
            $result = $sms->sendSMS($phone, $templateParams);
            $result['Code'] = 'Ok';
            if($result['Code'] == 'Ok'){
                //记录发送记录
                Db::connect('db_config_aiqi')->name('sms_log')->insert(['phone'=>$phone,'code'=>$rand,'type'=>$type,'ip'=>request()->ip()]);
                $redis = new Redis();
                $redis->set('sms_code_'.$phone, $rand, 300);
                $this->success('发送成功');
            }
            $this->error('发送失败');
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 退出登录
     */
    public function logout(){
       $token = $this->request->param('token');
        $redis = new Redis();
        $redis ->rm($token);
//        Session::delete('palyerinfo');

        $this->success('退出成功');
    }


    /** 实名认证 姓名、身份证号
     * @realname 姓名
     * @card_id 身份证号
     * @return bool
     */
    public function checkUserAuth($realname, $card_id) {
        
    }

}